package com.tbl.common.utils;

import org.apache.commons.lang3.Validate;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * ReflectUtils工具
 * @author 70486
 */
public class ReflectUtils {

        /**
         * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
         */
        public static Object getFieldValue(final Object obj, final String fieldName) {
            Field field = getAccessibleField(obj, fieldName);

            if (field == null) {
                throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
            }

            Object result = null;
            try {
                result = field.get(obj);
            } catch (IllegalAccessException ignored) {
            }
            return result;
        }



    public static Field getAccessibleField(final Object obj, final String fieldName) {
        Validate.notNull(obj, "object can‘t be null");
        Validate.notBlank(fieldName, "fieldName can‘t be blank");
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                makeAccessible(field);
                return field;
            } catch (NoSuchFieldException e) {//NOSONAR
                // Field不在当前类定义,继续向上转型
                // new add
            }
        }
        return null;
    }


    public static void makeAccessible(Field method) {
        boolean flag = (!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible();
        if (flag) {
            method.setAccessible(true);
        }
    }

}
